//
//  MyLinkList.m
//  oc_algorithm
//
//  Created by zp on 2021/1/27.
//

#import "SingleLinkList.h"

@interface SingleLinkList()

@property(nonatomic, assign)int size;

@end

@implementation SingleLinkList

-(id)init
{
    if (self = [super init]) {
        _size = 0;
        _head = [[ListNode alloc] initWithValue:0];
    }
    return self;
}

-(int)size
{
    return _size;
}

-(int)getItemAtIndex:(int)index
{
    if (index < 0 || index >= _size)
        return -1;
    ListNode *pre = self.head;
    for (int i = 0; i <= index; i++)
    {
        pre = pre.next;
    }
    return pre.val;
}

-(void)addItemAtHead:(int)value
{
    [self insertItem:value atIndex:0];
}

-(void)addItemAtTail:(int)value
{
    [self insertItem:value atIndex:self.size];
}

-(void)insertItem:(int)value atIndex:(int)index
{
    if (index < 0)
        index = 0;
    if (index > self.size)
        return;
    
    _size++;
    ListNode *pre = self.head;
    for (int i = 0; i < index; i++) {
        pre = pre.next;
    }
    ListNode *node = [[ListNode alloc] initWithValue:value];
    node.next = pre.next;
    pre.next = node;
}

-(void)deleteItemAtIndex:(int)index
{
    if (index < 0)
        index = 0;
    if (index >= _size) {
        return;
    }
    _size--;
    //删除链表节点的关键是找到index-1位置的节点
    ListNode *pre = self.head;
    for (int i = 0; i < index; i++) {
        pre = pre.next;
    }
    pre.next = pre.next.next;
}

-(void)insertNodes:(NSArray *)array atIndexes:(NSIndexSet *)indexes
{
    
}

- (NSString *)description
{
    NSMutableString *retString = [[NSMutableString alloc] initWithString:@"LinkList:\n"];
    ListNode *node = self.head;
    while (node.next) {
        node = node.next;
        [retString appendFormat:@" %d",node.val];
    }
    return [retString copy];
}

@end
